package server

import (
	"3-27zk/common/model/mysql"
	"3-27zk/common/model/redis"
	"3-27zk/common/proto/user"
	"context"
	"fmt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"math/rand"
	"time"
)

func SendSms(req *user.SendSmsReq) (*user.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000

	//sms, err := pkg.SendSms(req.Phone, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//if *sms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}

	set := redis.Rdb.Set(context.Background(), "sms"+req.Soures+req.Phone, code, time.Minute*10).Val()
	return &user.SendSmsResp{Sms: set}, nil
}

func Login(req *user.LoginReq) (*user.LoginResp, error) {
	val := redis.Rdb.Get(context.Background(), "smslogin"+req.Phone).Val()
	if val != req.SmsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	m := mysql.User{}
	getUser, err := m.GetUser(req.Phone)
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	if getUser.Phone == "" {
		m2 := mysql.User{
			Model:    gorm.Model{},
			Phone:    req.Phone,
			Password: req.Password,
		}
		err := m.Create(&m2)
		if err != nil {
			return nil, fmt.Errorf("注册失败")
		}
	}
	if getUser.Password != req.Password {
		return nil, fmt.Errorf("密码错误")
	}
	return &user.LoginResp{Greet: "登录成功"}, nil
}

func OrderAdd(req *user.OrderAddReq) (*user.OrderAddResp, error) {
	newString := uuid.NewString()
	order := mysql.Order{
		Model:    gorm.Model{},
		UserId:   int(req.UserId),
		OrderSn:  newString,
		Name:     req.Name,
		RoomType: int(req.RoomType),
		People:   req.People,
		Times:    req.Times,
		Price:    float64(req.Price),
		Person:   req.Person,
		Types:    int(req.Types),
	}
	err := order.Create(&order)
	if err != nil {
		return nil, fmt.Errorf("订单添加失败")
	}
	return &user.OrderAddResp{Success: "订单添加成功"}, nil
}

func OrderList(req *user.OrderListReq) (*user.OrderListResp, error) {
	order := mysql.Order{}
	list, err := order.OrderList()
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	var lists []*user.List
	for _, o := range list {
		lists = append(lists, &user.List{
			UserId:   int64(o.UserId),
			OrderSn:  o.OrderSn,
			Name:     o.Name,
			RoomType: int64(o.RoomType),
			People:   o.People,
			Times:    o.Times,
			Price:    float32(o.Price),
			Person:   o.Person,
			Types:    int64(o.Types),
		})
	}
	return &user.OrderListResp{List: lists}, nil
}
